package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.CuisineModel;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public List<ProductModel> findAll(ProductModel model) {
        String sql = "select t1.*,t2.name as cuisine_name from product t1 left join cuisine t2\n" +
                "on t1.cuisine_id=t2.id order by t1.id desc ";
        sql += " limit " + (model.getPage() - 1) * model.getLimit() + "," + model.getLimit() + "";
        return getList(sql);
    }

    @Override
    public Integer add(ProductModel productModel) {
        return null;
    }

    @Override
    public Integer getCount(ProductModel model) {
        String sql = "select count(*) as count from product t1,cuisine t2\n" +
                "where t1.cuisine_id=t2.id order by t1.id desc ";
        ResultSet resultSet = JDBC.query(sql);
        try {
            while (resultSet.next()) {
                return resultSet.getInt("count");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public ProductModel findById(ProductModel productModel) {
        return null;
    }

    @Override
    public Integer update(ProductModel productModel) {
        return null;
    }

    @Override
    public Integer del(ProductModel productModel) {
        return null;
    }

    @Override
    public Integer enable(ProductModel productModel) {
        return null;
    }

    private List<ProductModel> getList(String sql) {
        ResultSet resultSet = JDBC.query(sql);
        List<ProductModel> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                ProductModel model = new ProductModel();

                model.setId(resultSet.getInt("id"));
                model.setNormalPrice(resultSet.getBigDecimal("normal_price"));
                model.setName(resultSet.getString("name"));
                model.setImg(resultSet.getString("img_href"));
                model.setCreateTime(resultSet.getString("create_time"));
                model.setUpdateTime(resultSet.getString("update_time"));
                model.setEnable(resultSet.getInt("enable"));
                model.setRemark(resultSet.getString("remark"));
                model.setCuisineName(resultSet.getString("cuisine_name"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
